package org.jeecg.modules.basic.job;

import jdk.nashorn.internal.runtime.regexp.joni.ast.StringNode;
import lombok.SneakyThrows;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import java.io.File;
import java.io.IOException;

import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.ContentType;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class WechatFileMessageSenderJob implements Job {
    private static final String corp_id = "ww7d74522b769b9eff";
    private static final String corp_secret = "_OwzkeoH2zrIdkq4A6nwizR9lgvvbve4IwG2LfyfCAk";
    private static final String agent_id = "1000002";
    private static final String to_user = "Zi|SunZhengWu|XiaoNingBaBa";
    private static final String server_url = "https://qyapi.weixin.qq.com/cgi-bin/";
    private static final String file_type = "file";
    private static final String file_path = "C:\\Users\\Lenovo\\Desktop\\test\\未归记录.xlsx";
//    private static final String cache_path = "/docs/cache/";

    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取access_token
        String accessTokenUrl = server_url + "gettoken?corpid=" + corp_id + "&corpsecret=" + corp_secret;
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(accessTokenUrl);
        HttpResponse response = client.execute(post);
        String accessToken = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject jsonObject = new JSONObject(accessToken);
        String accessTokenValue = jsonObject.getString("access_token");

        // 调用上传文件接口，获取media_id，推送要用
        String uploadUrl = server_url + "media/upload?access_token=" + accessTokenValue + "&type=" + file_type;
        File file = new File(file_path);
        HttpEntity multipartEntity = MultipartEntityBuilder.create()
                .addBinaryBody("media", file, ContentType.DEFAULT_BINARY, file.getName())
                .build();
        post = new HttpPost(uploadUrl);
        post.setEntity(multipartEntity);
        response = client.execute(post);
        String mediaId = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject mediaJsonObject = new JSONObject(mediaId);
        String mediaIdValue = mediaJsonObject.getString("media_id");

        // 把需要的必填项填进去
        JSONObject messageJsonObject = new JSONObject();
        messageJsonObject.put("touser", to_user);
        messageJsonObject.put("msgtype", file_type);
        messageJsonObject.put("agentid", agent_id);
        JSONObject fileObject = new JSONObject();
        fileObject.put("media_id", mediaIdValue);
        messageJsonObject.put("file", fileObject);

        // 调用推送信息接口
        try {
            String messageSendUrl = server_url + "message/send?access_token=" + accessTokenValue;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(messageSendUrl);
            httpPost.setHeader("Content-Type", "application/json");
            String jsonString = messageJsonObject.toString();
            HttpEntity entity = new StringEntity(jsonString);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("返回值================" + statusCode);
            if (statusCode == 200) {
                String responseBody = EntityUtils.toString(httpResponse.getEntity());
                System.out.println("Response Body==============" + responseBody);
            } else {
                System.out.println("发送信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
